# -*- coding: utf-8 -*-
"""
@Time    : 2022/8/31 23:07
@Author  : huanghuang
"""
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from typing import List, Union, Dict

from common.g.g import G_LOGGER


class EmailSender:

    def __init__(self,
                 name: str,
                 sender: str,
                 thr_mail_host: str,
                 thr_mail_port: int,
                 thr_mail_user: str,
                 thr_mail_token: str
                 ):
        if thr_mail_port == 25:
            self.__client = smtplib.SMTP(host=thr_mail_host, port=thr_mail_port)
        else:
            self.__client = smtplib.SMTP_SSL(host=thr_mail_host, port=thr_mail_port)
        self.__client.login(user=thr_mail_user, password=thr_mail_token)
        self.__sender = sender
        self.__name = name

    @property
    def sender(self):
        return self.__sender

    @property
    def client(self):
        return self.__client

    @property
    def name(self):
        return self.__name

    def _build_msg(self, msg: str, subject: str, to, msg_type: str, filepath_list):
        if isinstance(to, (list, tuple)):
            to = ";".join(to)
        if filepath_list:
            m = MIMEMultipart()
            m["From"] = formataddr((self.name, self.sender), "utf-8")
            m["To"] = Header(to, "utf-8")
            m["Subject"] = Header(subject, "utf-8")

            for f in filepath_list:
                att = MIMEText(open(f["filepath"], "rb").read(), "base64", "utf-8")
                att["Content-Type"] = 'application/octet-stream'
                att["Content-Disposition"] = 'attachment; filename="{}"'.format(f["filename"])  # 中文名乱码
                m.attach(att)
            return m
        else:
            m = MIMEText(msg, msg_type, "utf-8")
            m["From"] = formataddr((self.name, self.sender), "utf-8")
            m["To"] = Header(to, "utf-8")
            m["Subject"] = Header(subject, "utf-8")
            return m

    def _send(self, msg, to):
        try:
            res = self.__client.sendmail(self.sender, to, msg.as_string())
            G_LOGGER.info(f"发送邮件响应:{res}")
            return True, "发送邮件成功"
        except smtplib.SMTPException as e:
            G_LOGGER.exception(f"发送邮件异常:to={to} msg={msg} \n{e}")
            return False, "发送邮件失败"

    def send(self, subject: str, msg: str, to: Union[str, List[str]], filepath_list: List[Dict[str, str]] = None):
        _msg = self._build_msg(msg, subject, to, msg_type="plain", filepath_list=filepath_list)
        return self._send(_msg, to)

    def send_html(self, subject: str, msg: str, to: Union[str, List[str]], filepath_list: List[Dict[str, str]] = None):
        _msg = self._build_msg(msg, subject, to, msg_type="html", filepath_list=filepath_list)
        return self._send(_msg, to)


if __name__ == '__main__':
    email_config = {
        "name": "发送邮件",
        "sender": "1436293318@qq.com",
        "thr_mail_host": "smtp.qq.com",
        "thr_mail_port": "465",
        "thr_mail_user": "1436293318@qq.com",
        "thr_mail_token": ""
    }
    es = EmailSender(**email_config)
    msg = mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="https://www.baidu.com">这是一个链接</a></p>
"""
    print(es.send("subject", msg, "2409561687@qq.com", filepath_list=[{"filename": "this is file文件", "filepath": "./email_util.py"}]))
